//files
AddCSLuaFile("cl_init.lua");
AddCSLuaFile("shared.lua");
include("shared.lua")

ENT.DebrisModels =
{
	Model("models/props_debris/metal_panelshard01a.mdl"),
	Model("models/props_debris/metal_panelshard01b.mdl"),
	Model("models/props_debris/metal_panelshard01c.mdl"),
	Model("models/props_debris/metal_panelshard01d.mdl")
}

//when initializing
function ENT:Initialize()

	//info
	self.Entity:SetModel("models/Items/AR2_Grenade.mdl");
	self.Entity:PhysicsInit(SOLID_VPHYSICS);
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS);
	self.Entity:SetSolid(SOLID_VPHYSICS);

	//physics object
	local Physics = self.Entity:GetPhysicsObject();

	//if valid
	if ValidEntity(Physics) then

		//wake
		Physics:Wake();

	end

end

//when colliding
function ENT:PhysicsCollide(Data,Physics)

	//effect data
	local FX = EffectData();
	FX:SetStart(self.Entity:GetPos());
	FX:SetOrigin(self.Entity:GetPos());
	FX:SetNormal(Data.HitNormal);
	FX:SetScale(1)

	//effect
	util.Effect("Explosion",FX)

	//damage
	util.BlastDamage(self.Entity,self.Entity:GetOwner(),self.Entity:GetPos(),230,90)

	for I = 1,6 do

		local Debris = ents.Create("prop_physics");

		if ValidEntity(Debris) then

			local RandomModel = self.DebrisModels[math.random(1,#self.DebrisModels)];

			Debris:SetModel(RandomModel);
			Debris:SetCollisionGroup(COLLISION_GROUP_WORLD);
			Debris:SetPhysicsAttacker(self.Entity:GetOwner());
			Debris:SetPos(self.Entity:GetPos() + Data.HitNormal * 5);
			Debris:SetAngles(Angle(math.Rand(1,360),math.Rand(1,360),math.Rand(1,360)));
			Debris:Spawn();
			Debris:Activate();

			local Physics = Debris:GetPhysicsObject();

			if ValidEntity(Physics) then

				local Fire = ents.Create("env_fire_trail");

				if ValidEntity(Fire) then

					Fire:SetKeyValue("spawnrate","3");
					Fire:SetKeyValue("firesprite","sprites/firetrail.spr");
					Fire:SetPos(Debris:GetPos());
					Fire:SetParent(Debris);
					Fire:Spawn();
					Fire:Activate();

					Debris.FireEnt = Fire;

					local Dir = Data.HitNormal;
					local Ang = Dir:Angle();

					Ang:RotateAroundAxis(Ang:Right(),math.Rand(-50,50));
					Ang:RotateAroundAxis(Ang:Forward(),math.Rand(-50,50));
					Ang:RotateAroundAxis(Ang:Up(),math.Rand(-50,50));
					Ang:RotateAroundAxis(Ang:Right(),90);

					Dir = Ang:Up();

					Physics:ApplyForceCenter(Physics:GetMass() * Dir * math.Rand(1500,2000));

					timer.Create("smod.KillDebris"..Debris:EntIndex(),10,1,
					function()

						timer.Destroy("smod.KillDebris"..Debris:EntIndex());

						Debris.FireEnt:Remove();
						Debris:Remove();

					end)

				else

					Debris:Remove();

				end

			else

				Debris:Remove();

			end

		end

	end

	//remove us
	self.Entity:Remove();

end 